﻿/*
ToolbarModule is a liteGrid plug-in that adds a simple toolbar to
liteGrid.  It also adds method named "addToolbarButton" to liteGrid
that can be used to add buttons to the toolbar.  

Author: MBH
DateAuthored: 7/17/09  
*/

//Adds a toolbar to liteGrid and makes it available for other
//modules to use. 
function ToolbarModule() {
	var base = this;

	//Adds a footer/header
	base.initialize = function(liteGrid, options) {
		base.liteGrid = liteGrid;

		base.liteGrid.$el.bind("initializationComplete", base.addToolbar);

		base.options = $.extend({}, ToolbarModule.defaultOptions, options);

		//This module adds toolbar support to liteGrid.  Other modules can use this function
		//to add new buttons.
		liteGrid.addToolbarButton = base.addToolbarButton;

		//Go ahead and make the toolbar so that other modules can use it.
		base.buttonBar = $("<div class='ui-widget-header toolbar'></div>");
	}

	//Callback that is run once initialization of liteGrid is complete.  This
	//adds a toolbar to the table.
	base.addToolbar = function() {

		//Make sure there is a div for the footer.
		if (!base.liteGrid.footerDiv) {
			console.error("No footer found on the div, can't add a toolbar.  Make sure LayoutManager is already running.");
			return;
		}

		//Add buttons.
		$(base.options.toolbarButtons).each(function() {
			base.addToolbarButton(this);
		});

		//Add the toolbar to the appropriate container.
		if (base.options.toolbarLocation == "footer") {
			base.liteGrid.footerDiv.append(base.buttonBar);
		}
		else if (base.options.toolbarLocation == "header") {
			base.liteGrid.headerDiv.append(base.buttonBar);
		}
		//If it isn't a built-in location, assume it is a jQuery selector.
		else {
			$(base.options.toolbarLocation).append(base.buttonBar);
		}
	}

	//Adds the specified button to the toolbar.
	//Buttons must have text, an icon (a CSS class), and an optional action.
	base.addToolbarButton = function(buttonInfo) {
		var button = $("<div class='button'><span class='ui-icon " + buttonInfo.icon + "'></span>" + buttonInfo.text + "</div>");

		button.click(function() {

			base.liteGrid.$el.trigger("toolbarButtonClicked", [button, buttonInfo]);

			//Fire the custom action.
			if (buttonInfo.action) {
				buttonInfo.action();
			}

		});

		//NOTE: The hover and mouseenter/leave events do not work correctly, so mouseover/out are used instead.
		button.mouseover(function() { $(this).addClass("ui-state-hover"); });
		button.mouseout(function() { $(this).removeClass("ui-state-hover"); });

		base.buttonBar.append(button);
	}
}
ToolbarModule.defaultOptions = { toolbarButtons: [], toolbarLocation: "footer" };